import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../../miniprogram_npm/@vant/weapp/dialog/dialog";
import {
  ajaxCreateOrder,
  ajaxGetPayParams
} from '../../../api/ordering'
import {
  ajaxGetOrderDetails,
  ajaxCancelOrder
} from '../../../api/order'
// 支付剩余时间定时器
let payTime = null;
// 支付时长
let payDuration = 1000 * 60 * 30;
const app = getApp();
// 防止重复创建订单
let isDisable = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    // 上页面数据
    prevParams: {},
    //收展
    isSlideShow: false,
    // 支付倒计时
    payTimeText: '',
    pageData: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    Toast.loading({
      message: '正在加载',
      forbidClick: true,
      duration: 0
    });
    try {
      let prevParams = null;
      // 我的页面成为年度会员-选择门店-入口参数
      if (options.orderId) {
        prevParams = {
          orderId: options.orderId
        }
      } else {
        // 获取上页面传递的数据
        let {
          'data': prevParamsData
        } = await app.getPrevPageData(this);
        prevParams = prevParamsData
      }
      let pageData = null;
      // 有订单id调用接口查详情数据
      if (prevParams.orderId) {
        let {
          data
        } = await ajaxGetOrderDetails({
          orderId: prevParams.orderId
        });
        pageData = data || {};
      } else {
        // 没有订单id使用传递的数据
        pageData = {
          productInfoList: JSON.parse(JSON.stringify(prevParams.list || [])),
          totalPay: prevParams.totalMoney || 0,
          sumQuantity: prevParams.totalNum || 0,
        }
      }
      pageData = Object.assign({}, (pageData || {}), {
        productInfoList: pageData.productInfoList || [],
        // 门店信息
        ...(prevParams.orderId ? {
          shopName: pageData.shopName,
          distance: pageData.distance
        } : {
          shopName: app.globalData.shopInfo.shopName,
          distance: app.globalData.shopInfo.distance
        })
      })
      this.setData({
        prevParams: prevParams || {},
        pageData
      })
      if (prevParams.orderId) {
        //非待支付状态跳转至详情页面
        if (pageData.orderStatus != 0) {
          this.goDetailsPage();
        } else {
          // 开启支付倒计时
          this.setOrderPayTime(true);
        }
      }
      await app.myNextTick()
      Toast.clear();
    } catch (err) {
      await app.myNextTick()
      Toast.clear();
      Toast(err.msg || '错误')
    }
  },
  //展开收起更多商品
  tabSlideShow() {
    this.setData({
      isSlideShow: !this.data.isSlideShow
    })
  },
  //启动关闭倒计时
  setOrderPayTime(isRun) {
    if (isRun) {
      let {
        createTime
      } = this.data.pageData;
      if (payTime || !createTime) {
        return;
      }
      if (app.getTimeStamp(createTime) + payDuration < Date.now()) {
        //订单倒计时过期跳转致详情页面
        this.goDetailsPage()
        return;
      }
      this.updateOrderPayTime();
      payTime = setInterval(() => {
        this.updateOrderPayTime();
      }, 1000)
    } else {
      clearInterval(payTime)
      payTime = null;
    }
  },
  // 更新倒计时数值
  updateOrderPayTime() {
    let {
      createTime
    } = this.data.pageData;
    //时间已过
    if (app.getTimeStamp(createTime) + payDuration < Date.now()) {
      //订单倒计时过期跳转致详情页面
      this.goDetailsPage()
      return;
    }
    let nowtime = new Date(), //获取当前时间
      endtime = app.getTimeStamp(createTime); //定义结束时间
    let lefttime = endtime + payDuration - nowtime.getTime(), //距离结束时间的毫秒数
      leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)), //计算天数
      lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24), //计算小时数
      leftm = Math.floor(lefttime / (1000 * 60) % 60), //计算分钟数
      lefts = Math.floor(lefttime / 1000 % 60); //计算秒数
    let supplement = (value) => {
      return value < 10 ? '0' + value : value;
    }
    let payTimeText = supplement(leftm) + ":" + supplement(lefts); //返回倒计时的字符串
    this.setData({
      payTimeText
    })
  },
  //订单倒计时过期跳转致详情页面
  goDetailsPage() {
    this.setOrderPayTime(false);
    wx.navigateBack({
      delta: 1,
      complete() {
        wx.showToast({
          title: '订单支付时间过期或已支付状态',
          icon: 'none',
          duration: 2000
        })
      }
    })
    // app.commonToPage(`/pages/order/orderDetails/index?orderId=${this.data.prevParams.orderId}`, 'redirectTo')
  },
  // 创建订单
  createOrder() {
    return new Promise(async (resolve, reject) => {
      try {
        // 整理套餐和商品
        let packageIdList = [],
          productIdList = [];
        this.data.prevParams.list.forEach(item => {
          let obj = {
            itemQuantity: item.num
          }
          if (item.packageId) {
            obj.packageId = item.packageId;
            packageIdList.push(obj);
          } else {
            obj.productId = item.productId;
            productIdList.push(obj);
          }
        })
        // 创建订单
        let {
          data
        } = await ajaxCreateOrder({
          packageIdList,
          productIdList,
          orderSource: app.globalData.shopInfo.shopId
        });
        resolve(data);
      } catch (err) {
        reject(err);
      }
    })
  },
  //获取支付参数
  async getPayParams(orderId) {
    return new Promise(async (resolve, reject) => {
      try {
        let {
          data
        } = await ajaxGetPayParams({
          orderId
        })
        resolve(data);
      } catch (err) {
        reject(err);
      }
    })
  },
  // 支付订单
  async payOrder(orderId) {
    return new Promise(async (resolve, reject) => {
      try {
        //获取支付参数
        let getPayParamsResp = await this.getPayParams(orderId);
        let data = getPayParamsResp || {};
        wx.requestPayment({
          "appId": app.globalData.config.server.APPID,
          "timeStamp": data.timeStamp,
          "nonceStr": data.nonceStr,
          "package": `prepay_id=${data.prepayId}`,
          "signType": data.signType,
          "paySign": data.paySign,
          "success": (res) => {
            //支付成功
            resolve({
              isOk: true
            });
          },
          "fail": (err) => {
            console.log(err);
            if (!this.data.prevParams.orderId) {
              //支付取消
              resolve({
                isOk: false
              });
            } else {
              reject(err.errMsg == 'requestPayment:fail cancel' ? {
                msg: '支付取消'
              } : {
                msg: err.errMsg
              })
            }
          }
        })

      } catch (err) {
        //支付失败
        resolve({
          isOk: false,
          msg: (err && err.msg) || '支付失败'
        });
      }
    })
  },
  // 支付下单
  async pay() {
    if (isDisable) {
      return;
    }
    isDisable = true;
    Toast.loading({
      message: '正在处理',
      forbidClick: true,
      duration: 0
    });

    try {
      let orderId = null,
        // 支付金额
        totalPay = null;
      // 已有订单,直接支付
      if (this.data.prevParams.orderId) {
        orderId = this.data.prevParams.orderId;
      } else {
        // 正常流程，创建订单
        let createOrderResp = await this.createOrder();
        orderId = createOrderResp.orderId;
        totalPay = createOrderResp.totalPay;
        // 清空购物车
        this.clearShoppingCart();
      }

      let isOk = true,
        msg = '支付成功';

      // 已存在订单 或 订单需要支付金额
      if (this.data.prevParams.orderId || totalPay > 0) {
        // 支付订单
        let payObj = await this.payOrder(orderId);
        isOk = payObj.isOk;
        msg = payObj.msg;
      }

      // 正常流程，支付成功或取消id储存
      if (!this.data.prevParams.orderId) {
        app.storeModules.order.data[isOk ? 'orderId' : 'cancelOrderId'] = orderId;
      }
      isDisable = false;
      Toast({
        type: isOk ? 'success' : 'fail',
        forbidClick: true,
        message: msg || (isOk ? '支付成功' : '支付取消'),
        onClose: () => {
          if (isOk) {
            this.openPopup();
            if (!this.data.prevParams.orderId) {
              //跳转到订单列表，订单列表会根据存储id带进详情页面
              app.commonToPage('/pages/order/index', 'switchTab')
            } else {
              // 直接将当前支付页面替换到详情页面
              app.commonToPage(`/pages/order/orderDetails/index?orderId=${this.data.prevParams.orderId}`, 'redirectTo')
            }
          } else {
            if (!this.data.prevParams.orderId) {
              //跳转到订单列表，订单列表会根据存储id带进详情页面
              app.commonToPage('/pages/order/index', 'switchTab')
            }
          }
        }
      });
    } catch (err) {
      this.failToast(err);
    }
  },
  // 是否设置过授权
  openPopup() {
    const _this = this;
    // 获取用户的当前设置，判断是否点击了“总是保持以上，不在询问”
    wx.getSetting({
      withSubscriptions: true, // 是否获取用户订阅消息的订阅状态，默认false不返回
      success(res) {
        // console.log('res.authSetting', res.authSetting)
        if (res.authSetting['scope.subscribeMessage']) {
          // console.log('用户点击了“总是保持以上，不再询问”')
        } else {
          // console.log('用户没有点击“总是保持以上，不再询问”则每次都会调起订阅消息')
          wx.showModal({
            title: '订阅通知',
            // showCancel: false,
            confirmColor: '#e61211',
            content: '是否订阅比赛开始提醒？',
            success(res) {
              //因为没有选择总是保持，所以需要调起授权弹窗再次授权
              _this.authorizationBtn();
            }
          })
        }
      }
    })
  },
  // 授权
  authorizationBtn() {
    wx.requestSubscribeMessage({
      tmplIds: ['lc9kofcfN9O5tUJMuocH8nDRo26fWouS63OWNGmEqXc'],
      success(res) {
        // console.log('授权成功')
      },
      fail(err) {
        console.log(err);
      }
    })
  },
  //失败
  async failToast(err) {
    isDisable = false;
    await app.myNextTick()
    Toast.clear();
    Toast((err && err.msg) || '错误')
  },
  // 寻找点单页面调用清空购物车方法
  clearShoppingCart() {
    let page = app.getQueryUrlPage('pages/ordering/index');
    if (page) {
      // 清空购物车数据
      if (page.clearShoppingCartHandle) {
        page.clearShoppingCartHandle();
      }
      // 删除此商铺本地购物车数据
      if (page.deleteShoppingCartStorage) {
        page.deleteShoppingCartStorage();
      }
    }
  },
  // 取消订单
  cancelOrder() {
    Dialog.confirm({
        message: `确定取消订单吗?`,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonColor: "#e61211",
        zIndex: 120,
      })
      .then(async () => {
        Toast.loading({
          message: '正在处理',
          forbidClick: true,
          duration: 0
        });
        try {
          await ajaxCancelOrder({
            orderId: this.data.prevParams.orderId
          })
          await app.myNextTick()
          Toast.clear();
          wx.navigateBack({
            delta: 1
          })
        } catch (err) {
          await app.myNextTick()
          Toast.clear();
          Toast(err.msg || '错误')
        }
      })
      .catch(() => {});
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setOrderPayTime(true);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setOrderPayTime(false);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setOrderPayTime(false);
  }
})